package com.ethan.controller;

import com.ethan.pojo.Category;
import com.ethan.pojo.Result;
import com.ethan.service.CategoryService;
import com.ethan.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public Result<List<Category>> list() {
        List<Category> categoryList= categoryService.list();
        return Result.success(categoryList);
    }

    @GetMapping("/detail")
    public Result<Category> findById(Integer id) {
        return Result.success(categoryService.findById(id));
    }

    @PostMapping("/add")
    public Result add(@RequestBody @Validated(Category.Add.class) Category category){
        //补充属性
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        category.setCreateUser((Integer) map.get("id"));
        categoryService.add(category);
        return Result.success();
    }

    @PostMapping("/update")
    public Result update(@RequestBody @Validated(Category.Update.class) Category category){
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        category.setCreateUser((Integer) map.get("id"));
        categoryService.update(category);
        return Result.success();
    }

    @PostMapping("/delete")
    public Result delete(Integer id){
        categoryService.delete(id);
        return Result.success();
    }

}
